from logging.config import fileConfig
from sqlalchemy import create_engine, pool
from alembic import context
import sys
from pathlib import Path

# 精确计算项目根目录路径
project_root = Path(__file__).resolve().parent.parent.parent  # backend/alembic -> backend -> parent -> demo_fastapi
sys.path.insert(0, str(project_root))

# 导入项目配置和模型
from backend.app.config import settings
from backend.app.db.db_models import Base

# Alembic配置
config = context.config
fileConfig(config.config_file_name)
target_metadata = Base.metadata

def run_migrations_offline():
    """Run migrations in 'offline' mode."""
    context.configure(
        url=settings.SQLALCHEMY_DATABASE_URL.replace("sqlite:///", "sqlite:///"+str(project_root)+"/"),
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"}
    )
    with context.begin_transaction():
        context.run_migrations()

def run_migrations_online():
    """Run migrations in 'online' mode."""
    connectable = create_engine(settings.SQLALCHEMY_DATABASE_URL)
    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata
        )
        with context.begin_transaction():
            context.run_migrations()

if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
